package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkSpaceService;
import com.sky.vo.*;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService{


    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private WorkSpaceService workSpaceService;

    private ArrayList<LocalDate> getDateList(LocalDate begin, LocalDate end){
        ArrayList<LocalDate> dateList=new ArrayList<>();
        while(!begin.equals(end)){
            dateList.add(begin);
            begin=begin.plusDays(1);
        }
        dateList.add(end);
        return dateList;
    }


    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        //查找下单时间在begin~end之间的订单

        List<LocalDate> dateList=getDateList(begin,end);

        List<Double> turnoverList=new ArrayList<>();
        for (LocalDate localDate : dateList) {
            LocalDateTime begin1=LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime end1=LocalDateTime.of(localDate, LocalTime.MAX);

            Map<String,Object> map=new HashMap<>();
            map.put("status", Orders.COMPLETED);
            map.put("begin",begin1);
            map.put("end",end1);
            //如果当天营业额为0，实际上返回的是null，而不是0
            //使用 sql函数 coalesce(sum(amount), 0.0)，当为null是返回0.0
            Double total= orderMapper.sumByMap(map);
            turnoverList.add(total);
        }

        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList=getDateList(begin,end);
        List<Long> totalUserList=new ArrayList<>();
        List<Long> newUserList=new ArrayList<>();

        //获取begin那天的用户，后面的可以通过newUserList计算而得
        Long total= userMapper.count(LocalDateTime.of(begin,LocalTime.MAX));
        totalUserList.add(total);

        for (LocalDate localDate : dateList) {
            LocalDateTime begin1=LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime end1=LocalDateTime.of(localDate, LocalTime.MAX);

            //查找这天新增的用户
            Map<String,Object> map=new HashMap<>();
            map.put("begin",begin1);
            map.put("end",end1);
            Long sum= userMapper.sumByMap(map);
            newUserList.add(sum);
            if(!localDate.equals(begin)){
                total+=sum;
                totalUserList.add(total);
            }

        }

        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .build();
    }

    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = getDateList(begin, end);
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        Integer totalOrderCount=0;
        Integer validOrderCount=0;

        for (LocalDate localDate : dateList) {
            LocalDateTime begin1=LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime end1=LocalDateTime.of(localDate, LocalTime.MAX);
            Orders orders=new Orders();
            List<OrderVO> list = orderMapper.list(null, begin1, end1);

            Integer count=  (list==null?0:list.size());
            totalOrderCount+=count;
            orderCountList.add(count);

            orders.setStatus(Orders.COMPLETED);
            list=orderMapper.list(orders, begin1, end1);

            count= (list==null?0:list.size());
            validOrderCount+=count;
            validOrderCountList.add(count);

        }

        Double orderCompletionRate=0.00;
        if(totalOrderCount!=0){
            DecimalFormat decimalFormat = new DecimalFormat("#.00");
            orderCompletionRate=(double) validOrderCount/totalOrderCount;
            orderCompletionRate= Double.valueOf(decimalFormat.format(orderCompletionRate));
        }


        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime=LocalDateTime.of(begin,LocalTime.MIN);
        LocalDateTime endTime=LocalDateTime.of(end,LocalTime.MAX);

        List<GoodsSalesDTO> goodsSalesDTOList= orderMapper.getSalesTop10(beginTime,endTime);

        List<String> nameList = goodsSalesDTOList.stream().map((GoodsSalesDTO::getName)).collect(Collectors.toList());
        List<Integer> numberList = goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());



        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();
    }

    @Override
    public void exportExcel(HttpServletResponse response) {

        LocalDate begin=LocalDate.now().minusDays(30);
        LocalDate end=LocalDate.now().minusDays(1);

        //总览数据
        BusinessDataVO businessData = workSpaceService.getBusinessData(begin, end);



        try( InputStream in = this.getClass().getClassLoader().getResourceAsStream("fileTemplate/运营数据报表模板.xlsx");
             XSSFWorkbook excel=new XSSFWorkbook(in);
             ServletOutputStream outputStream = response.getOutputStream()
        ) {
            XSSFSheet sheet = excel.getSheet("Sheet1");
            sheet.getRow(1).getCell(1).setCellValue("时间："+begin+"至"+end);

            sheet.getRow(3).getCell(2).setCellValue(businessData.getTurnover());
            sheet.getRow(3).getCell(3).setCellValue(businessData.getOrderCompletionRate());
            sheet.getRow(3).getCell(4).setCellValue(businessData.getNewUsers());

            sheet.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());
            sheet.getRow(4).getCell(3).setCellValue(businessData.getUnitPrice());

            for(int i=0;i<30;i++){
                 businessData = workSpaceService.getBusinessData(begin, begin);

                XSSFRow row = sheet.getRow(i + 7);

                row.getCell(1).setCellValue(begin.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
                begin= begin.plusDays(1);
            }

            excel.write(outputStream);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }



}
